package weibo;

import user.UserSession;
import utils.JsonOut;
import utils.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet(name = "DeleteCommentServlet")
public class DeleteCommentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        String email = UserSession.getUserSessionEmail(session);

        PrintWriter out = response.getWriter();
        if (email == null || email.isEmpty()){
            out.println(JsonOut.error(220, "not_login"));
            return;
        }

        String commentId = request.getParameter("comment_id");
        if (commentId == null || commentId.isEmpty()){
            out.println(JsonOut.error(201, "no_comment_id"));
            return;
        }

        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(commentId);
        if(!isNum.matches()){
            out.println(JsonOut.error(202, "bad_comment_id"));
            return;
        }

        if (!(new MysqlUtils()).canDeleteComment(email, commentId)){
            out.println(JsonOut.error(202, "cannot_delete_comment"));
            return;
        }

        if (!(new MysqlUtils()).deleteComment(commentId)){
            out.println(JsonOut.error(500, "sql_sth_wrong"));
            return;
        }

        out.println(JsonOut.error(0, "delete_comment_success"));

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(JsonOut.error(403, "forbidden"));
    }
}
